﻿import json;
import mysql.connector;
import datetime;
import requests;
import re;
import time;
import postYx;
import toke;


class yueque():

	def getToke(self):


		url='https://api.yunque360.com/v1/worker/account/login'

		parmeg={"password":"591591","fullname":"1005@qmjj","identifier":"1005@qmjj"} #'has_user':1,'last_event_time_start':'2020-07-20 00:00:00','last_event_time_end':'2020-07-21 23:59:59',

		r=requests.post(url=url,data=parmeg)

		data=json.loads(r.text)

		toke='Bearer '+data['result']['token']

		mydb = mysql.connector.connect(
		  host="localhost",       # 数据库主机地址
		  user="root",    # 数据库用户名
		  passwd="root",   # 数据库密码
		  database="weizandata"
		)
		mycursor = mydb.cursor()

		sql="UPDATE toke SET toke='" + toke + "' WHERE name_i='yq';"

		print(sql+'\n')

		mycursor.execute(sql)

		mydb.commit()

		print(mycursor.rowcount)

		return mycursor.rowcount



	def userLists(self,page=1,pagesize=10):

		tk=toke.toke()

		url='https://api.yunque360.com/v1/worker/wxuser/index'

		parmeg={'page':str(page),'order_by':'last_event_time','pagesize':str(pagesize)} #'has_user':1,'last_event_time_start':'2020-07-20 00:00:00','last_event_time_end':'2020-07-21 23:59:59',
		
		header=	{'Authorization':tk.getToke('yq')}

		r=requests.post(url=url,data=parmeg,headers=header)

		return r.text

	def userLianTianJiLu(self,open_id):

		tk=toke.toke()

		url='https://api.yunque360.com/v1/company/conversation/wechat-history'

		parmeg={'open_id':open_id}
		
		header=	{'Authorization':tk.getToke('yq')}

		r=requests.post(url=url,data=parmeg,headers=header)

		return r.text

	def remark(self,open_id):

		url='https://api.yunque360.com/v1/worker/user/info?uid='+open_id

		parmeg={}

		tk=toke.toke()
		
		header=	{'Authorization':tk.getToke('yq'),'Origin':'https://uworker.yunque360.com','Accept': 'application/json, text/plain, */*','Referer': 'https://uworker.yunque360.com/agent/wechat_history'}

		r=requests.get(url=url,data=parmeg,headers=header)

		rem=json.loads(r.text)['result']

		if('mobile' in rem):

			if(rem['talk_time']==None):

				rem['talk_time']=rem['last_event_time']


			if(rem['mobile']==''):

				if(rem['qq']==''):

					if(rem['weixin']==''):

						m=re.search(r'\d{11}',rem['showname'],re.S)

						if(m!=None):

							# print('showname=:'+rem['showname'])
							# print('mobile=:'+rem['mobile'])
							# print('last_event_time=:'+rem['last_event_time'])
							# print('open_id=:'+rem['open_id'])
							# print('last_worker=:'+rem['last_worker']['nickname'])
							# print('phone=:'+m.group(0))


							result={'showname':rem['showname'],'mobile':m.group(0),'last_event_time':rem['last_event_time'],'talk_time':rem['talk_time'],'open_id':rem['open_id'],'last_worker':rem['last_worker']['nickname']}

							return result

						else:

							return 0

					else:

						result={'showname':rem['showname'],'mobile':rem['weixin'],'last_event_time':rem['last_event_time'],'talk_time':rem['talk_time'],'open_id':rem['open_id'],'last_worker':rem['last_worker']['nickname']}

						return result

				else:

					result={'showname':rem['showname'],'mobile':rem['qq'],'last_event_time':rem['last_event_time'],'talk_time':rem['talk_time'],'open_id':rem['open_id'],'last_worker':rem['last_worker']['nickname']}

					return result


			else:

					# print('showname=:'+rem['showname'])
					# print('mobile=:'+rem['mobile'])
					# print('last_event_time=:'+rem['last_event_time'])
					# print('open_id=:'+rem['open_id'])
					# print('last_worker=:'+rem['last_worker']['nickname'])
					
					result={'showname':rem['showname'],'mobile':rem['mobile'],'last_event_time':rem['last_event_time'],'talk_time':rem['talk_time'],'open_id':rem['open_id'],'last_worker':rem['last_worker']['nickname']}

					return result

		else:


			return 0

		

	def yq(self,tol):

		pagesize=int(tol);

		list_data=json.loads(self.userLists())

		# print(list_data)

		total=int(tol)

		#total=list_data['result']['total'];

		page=int(total/pagesize)+1;

		for i in range(1,page):

			# print(json.loads(self.userLists(i,pagesize)))

			list_datai=json.loads(self.userLists(i,pagesize))['result']['data']

			j=0

			for listi in list_datai:

				j+=1

				lista=[];

				print('循环间距'+str(total)+'条')

				print('进度：'+str(((i*pagesize)/total)*100)+'%')

				print('子进度：'+str((j/len(list_datai))*100)+'%')

				open_id=listi['open_id'];

				appName=listi['app']['name'];

				rem=self.remark(open_id)

				if(rem!=0):

					if(rem != None):

						rem['appName']=appName

						lista.append(rem)

					#print('共计：'+str(len(lista))+'条')

						re=self.upDb('wxgongzhonghaophone',lista)

						print('插入：'+str(re)+'条')

	def upDb(self,table,dataI):

		mydb = mysql.connector.connect(
		  host="localhost",       # 数据库主机地址
		  user="root",    # 数据库用户名
		  passwd="root",   # 数据库密码
		  database="weizandata"
		)
		mycursor = mydb.cursor()
		upCount=0
		for item in dataI:

			val=[]
			filed=[]
			for key in item:

				filed.append(key)
				val.append('\"'+str(item[''+key+''])+'\"')

			filedStr=','.join(filed)
			valStr=','.join(val)
			sql="INSERT IGNORE INTO "+table+"("+filedStr+")value("+valStr+");"
			
			#sql="REPLACE INTO "+table+"("+filedStr+")value("+valStr+");"
			print(sql+'\n')

			mycursor.execute(sql)

			mydb.commit()

			rowcount=mycursor.rowcount	

			upCount=upCount+int(rowcount)

		return upCount
	def sleeptime(self,hour,min,sec):
		return hour*3600 + min*60 + sec;


if __name__=='__main__':

	yq=yueque()

	# yq.yq()

	ct=input('输入条目数：')

	print('执行。。。。。')

	yq.yq(ct)

	second = yq.sleeptime(0,0,2);

	errorCount=1

	while 1==1:

		time.sleep(second)

		print(time.strftime("%Y-%m-%d %H:%M:%S"))


		try:

			yq.yq(ct)

			if errorCount==0:

				yx=postYx.yx()

				to_list = ['450537144@qq.com'] #多用户使用的list

				yx.Mailer(to_list,th1="您的python脚本yuque.py恢复正常运行",Subject='服务器正常提示')#,unipath=r'F:\test.xlsx'

				errorCount=1

		except:

			yq.getToke()

			if(errorCount==1):

				yx=postYx.yx()

				to_list = ['450537144@qq.com'] #多用户使用的list
     
				yx.Mailer(to_list,th1="您的python脚本yuque.py出现故障请及时处理",Subject='服务器故障报警1')#,unipath=r'F:\test.xlsx'

				errorCount=0

			print("执行")
